var fs = require('fs');
var join = require('path').join;
var path = require('path');
const chalk = require('chalk');
var lowerCaseFirst = require('lower-case-first')

function routerData(name) {
    return (
`import React from 'react';
import { connect } from 'dva';
import style from '../less/${lowerCaseFirst(name)}.less';
class ${name} extends React.Component
{
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div></div>
        );
    }
}
export default connect(({${lowerCaseFirst(name)}}) => ({${lowerCaseFirst(name)}}))(${name});
`
    )
} 

function componentData(name) {
    return (
`import React from 'react';
import style from './index.less';
class ${name} extends React.Component
{
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div></div>
        );
    }
}
export default ${name};
`
    );
}

function create(type, param) {
    if(fs.exists(param.filePath)) {
        console.info(chalk.blue('文件已存在'));
        return;
    }else {
        mkdirsSync(param.filePath.substring(0,param.filePath.lastIndexOf('/')));
    }
    switch (type) {
        case 'router':
            writeTemplateFile(routerData, param.filePath, param.name);
            if(param.css){
                if(mkdirsSync(param.css.substring(0,param.css.lastIndexOf('/')))) {
                    writeTemplateFile(null, param.css, 'index');
                }
            }
            break;
        case 'component':
            writeTemplateFile(componentData, param.filePath, param.name);
            if(param.css){
                writeTemplateFile(null, param.css, 'index');
            }
            break;
        default:
            break;
    }
}

// 写模板
function writeTemplateFile(template, filePath, fileName) {
    if(template) {
        fs.writeFile(filePath,template(fileName),function(err){
            if(err) {
                return console.error(chalk.red(err));
            }
        })
    }else {
        fs.writeFile(filePath,'',function(err){
            if(err) {
                return console.error(chalk.red(err));
            }
        })
    }
    
}

//递归创建目录
function mkdirsSync(dirname) {  
    // console.log(dirname);  
    if (fs.existsSync(dirname)) {  
        return true;  
    } else {  
        if (mkdirsSync(path.dirname(dirname))) {  
            fs.mkdirSync(dirname, 0777);  
            return true;  
        }  
    }  
}  


module.exports = create;